package org.jtb.flickrportlet;

import java.io.IOException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.ReadOnlyException;
import javax.portlet.ValidatorException;
import javax.portlet.WindowState;

public class PrefsHandler {
    private PortletRequest request = null;
    private PrefsBean prefsBean;
    
    private PortletRequest getRequest() {
        if (request == null) {
            throw new IllegalStateException("request is not set");
        }
        return request;
    }
    
    public void setRequest(PortletRequest request) {
        this.request = request;
    }
    
    public void setUserName(String val) throws ReadOnlyException {
        getPreferences().setValue("userName", val);
    }
    
    private String getPreference(String key) {
        PortletPreferences prefs = getPreferences();
        String val = prefs.getValue(key, null);
        return val;
    }
    
    private int getIntPreference(String key) {
        PortletPreferences prefs = getPreferences();
        String val = prefs.getValue(key, null);
        
        return Integer.valueOf(val).intValue();
    }
    
    private void setPreference(String key, String val) throws ReadOnlyException {
        PortletPreferences prefs = getPreferences();
        prefs.setValue(key, val);
    }
    
    private PortletPreferences getPreferences() {
        PortletPreferences prefs = getRequest().getPreferences();
        return prefs;
    }
    
    public void store() throws IOException, ValidatorException {
        getPreferences().store();
    }
    
    public PrefsBean getPrefsBean() {
        return prefsBean;
    }
    
    public void setPrefsBean(PrefsBean prefsBean) {
        this.prefsBean = prefsBean;
        
        prefsBean.setUserName(getPreference("userName"));
                
        if (request.getWindowState() == WindowState.MAXIMIZED) {
            prefsBean.setPerPage(getIntPreference("perPageMaximized"));
        } else {
            prefsBean.setPerPage(getIntPreference("perPageMinimized"));
        }
    }
}
